//
//  NewReservationListViewController.m
//  Doctor1.0
//
//  Created by mk on 15/11/3.
//  Copyright (c) 2015年 cocoa-mk. All rights reserved.
//


#import "NewReservationListViewController.h"
#import "AppointmentViewController.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>


@interface NewReservationListViewController ()
{
    int updateIndex;
    
    BOOL selectBeginDate;
    int keyHeight;
    UITextField * textNow;
    PickView * viewDatepicker;
    UIDatePicker * datePickerBirthday;
    NSMutableArray * arrayPicture;
    
    NSString * str_end_time;
    NSString * str_stark_time;
}

@end

@implementation NewReservationListViewController

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [textNow resignFirstResponder];
    [txv_Disease_Dp resignFirstResponder];
     [self showPickerData:NO];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //创建预约单
    titleLabel.text = @"预约单";
    
    imageDescriptionBG.layer.masksToBounds = YES;
    imageDescriptionBG.layer.cornerRadius = 4;
    txv_Disease_Dp.layer.masksToBounds = YES;
    txv_Disease_Dp.layer.cornerRadius = 4;
    btnOIK.layer.masksToBounds = YES;
    btnOIK.layer.cornerRadius = 4;
    
    [scrollMain setAlwaysBounceVertical:YES];
    
    [self createPicker];
    
    arrayPicture = [[NSMutableArray alloc]initWithCapacity:0];
    [self setCaseImageView];
    [self setDoctorData];
}

//设置doctordata
-(void)setDoctorData
{
    labDocotrName.text = self.doctorData.name;
    labDepartment.text = self.doctorData.hpDeptName;
    labHospital.text = self.doctorData.hpName;
   
    //默认日期
    [btndateEnd setBackgroundImage:[[UIImage imageNamed:@"reservation_select_time_bg.png"] stretchableImageWithLeftCapWidth:30 topCapHeight:10] forState:UIControlStateNormal];
    [btndataBegin setBackgroundImage:[[UIImage imageNamed:@"reservation_select_time_bg.png"] stretchableImageWithLeftCapWidth:30 topCapHeight:10] forState:UIControlStateNormal];
    selectBeginDate = YES;
    
    NSString * strbegDate = [self getOrAfterAFewDaysAgoWithDate:@"" days:1 back:YES];
    [btndataBegin setTitle:strbegDate forState:UIControlStateNormal];
   
    NSString * strendDate = [self getOrAfterAFewDaysAgoWithDate:@"" days:8 back:YES];
    [btndateEnd setTitle:strendDate forState:UIControlStateNormal];
    
    viewDatepicker.pickTitle.text = strbegDate;
    str_end_time = strendDate;
    str_stark_time = strbegDate;
}


#pragma mark 设置上传病例图片
-(void)setCaseImageView
{
    int pickerW = (appScreenWidth-60)/3;
    int pickerViewH = 10;
    
    if (arrayPicture.count < 3)
        pickerViewH = pickerW+10;
   else if (arrayPicture.count < 6 && arrayPicture.count >= 3)
        pickerViewH = pickerW*2+20;
   else if (arrayPicture.count >= 6)
        pickerViewH = pickerW*3+30;
    
    for (NSLayoutConstraint *constraints in [viewimages constraints])
    {
        if (constraints.firstItem == viewimages && constraints.firstAttribute == NSLayoutAttributeHeight)
        {
            constraints.constant = pickerViewH;
            break;
        }
    }
    
    for (NSLayoutConstraint *constraints in [btnPicker1 constraints])
    {
        if (constraints.firstItem == btnPicker1 && constraints.firstAttribute == NSLayoutAttributeHeight)
        {
            if (constraints.constant == 60)
            {
               constraints.constant = pickerW;
                 break;
            }
        }
    }
    
    btnPicker2.hidden = !(arrayPicture.count>=1);
    btnPicker3.hidden = !(arrayPicture.count>=2);
    btnPicker4.hidden = !(arrayPicture.count>=3);
    btnPicker5.hidden = !(arrayPicture.count>=4);
    btnPicker6.hidden = !(arrayPicture.count>=5);
    btnPicker7.hidden = !(arrayPicture.count>=6);
    btnPicker8.hidden = !(arrayPicture.count>=7);
    btnPicker9.hidden = !(arrayPicture.count>=8);
    
    [btnPicker1 setImage:(arrayPicture.count>=1)?[arrayPicture objectAtIndex:0]:[UIImage imageNamed:@"add.png"] forState:UIControlStateNormal];
    [btnPicker2 setImage:(arrayPicture.count>=2)?[arrayPicture objectAtIndex:1]:[UIImage imageNamed:@"add.png"] forState:UIControlStateNormal];
    [btnPicker3 setImage:(arrayPicture.count>=3)?[arrayPicture objectAtIndex:2]:[UIImage imageNamed:@"add.png"] forState:UIControlStateNormal];
    [btnPicker4 setImage:(arrayPicture.count>=4)?[arrayPicture objectAtIndex:3]:[UIImage imageNamed:@"add.png"] forState:UIControlStateNormal];
    [btnPicker5 setImage:(arrayPicture.count>=5)?[arrayPicture objectAtIndex:4]:[UIImage imageNamed:@"add.png"] forState:UIControlStateNormal];
    [btnPicker6 setImage:(arrayPicture.count>=6)?[arrayPicture objectAtIndex:5]:[UIImage imageNamed:@"add.png"] forState:UIControlStateNormal];
    [btnPicker7 setImage:(arrayPicture.count>=7)?[arrayPicture objectAtIndex:6]:[UIImage imageNamed:@"add.png"] forState:UIControlStateNormal];
    [btnPicker8 setImage:(arrayPicture.count>=8)?[arrayPicture objectAtIndex:7]:[UIImage imageNamed:@"add.png"] forState:UIControlStateNormal];
    [btnPicker9 setImage:(arrayPicture.count>=9)?[arrayPicture objectAtIndex:8]:[UIImage imageNamed:@"add.png"] forState:UIControlStateNormal];
    
}

#pragma mark 创建pick
-(void)createPicker
{
    if (!viewDatepicker)
    {
        viewDatepicker = [[PickView alloc] init];
        viewDatepicker.delegate = self;
        viewDatepicker.backgroundColor = [UIColor whiteColor];
        viewDatepicker.tag = 100;
        [viewDatepicker setTranslatesAutoresizingMaskIntoConstraints:NO];
      //  viewDatepicker.pickMaxData = [dm dateFromString:@"2100-12-30"];
        [viewDatepicker setDataPick];
        [self.view addSubview:viewDatepicker];
        NSDictionary *views = NSDictionaryOfVariableBindings(viewDatepicker);
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0@1000-[viewDatepicker]-0@1000-|"
                                                                          options:0
                                                                          metrics:nil
                                                                            views:views]];
        
        NSLayoutConstraint *constraintHE = [NSLayoutConstraint constraintWithItem:self.view
                                                                        attribute:NSLayoutAttributeBottom
                                                                        relatedBy:NSLayoutRelationEqual
                                                                           toItem:viewDatepicker
                                                                        attribute:NSLayoutAttributeBottom
                                                                       multiplier:1
                                                                         constant:-206];
        [self.view addConstraint:constraintHE];
        
        NSLayoutConstraint *constraintV = [NSLayoutConstraint constraintWithItem:viewDatepicker
                                                                       attribute:NSLayoutAttributeHeight
                                                                       relatedBy:NSLayoutRelationEqual
                                                                          toItem:nil
                                                                       attribute:NSLayoutAttributeHeight
                                                                      multiplier:1
                                                                        constant:206];
        [self.view addConstraint:constraintV];
    }
    
}


#pragma mark =====btnClick=====

#pragma mark 提交
-(IBAction)btnUpdateMessage:(id)sender
{
    NSString * username =  TextNsString(txtUserName.text)
    NSString * disease =  TextNsString(txtDisease_name.text)
    NSString * dp =  TextNsString(txv_Disease_Dp.text)
    if (username.length ==0)
    {
        Alert(alerTitle, @"请填写患者姓名", @"确定")
        return;
    }
    if (disease.length ==0)
    {
        Alert(alerTitle, @"请填写疾病名称", @"确定")
        return;
    }
    if (dp.length ==0)
    {
        Alert(alerTitle, @"请填写疾病描述", @"确定")
        return;
    }
    
    if (arrayPicture.count == 0)
    {
        UIAlertView * aler = [[UIAlertView alloc]initWithTitle:alerTitle message:@"没有上传病例,可以在预约单详情修改" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"提交", nil];
        [aler show];
    }else
    {
        [self updateDataWithReservationList];
    }

}

#pragma mark 隐藏
-(IBAction)clickCanael:(id)sender
{
    [self showPickerData:NO];
}

#pragma mark 选择时间
-(IBAction)selectData:(id)sender
{
    [textNow resignFirstResponder];
    [txv_Disease_Dp resignFirstResponder];
    
    UIButton * btn = (UIButton *)sender;
    selectBeginDate = (btn == btndataBegin?YES:NO);
    
    if (!selectBeginDate)//结束时间设置最大值,最小值为开始时间7天之后
    {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        
        NSString * strbeg = [self getOrAfterAFewDaysAgoWithDate:str_stark_time days:7 back:YES];
        NSDate * minDate = [dateFormatter dateFromString:strbeg];
        
        NSString * strend = [self getOrAfterAFewDaysAgoWithDate:str_stark_time days:365 back:YES];
        NSDate * maxDate = [dateFormatter dateFromString:strend];
        [viewDatepicker setPickViewMaxData:maxDate];
        [viewDatepicker setPickViewMinData:minDate];
        [viewDatepicker setDefoultData:minDate];//默认
        viewDatepicker.pickTitle.text = str_end_time;
    }
    else
    {
       //最小值当前天数+1 最大无线 默认上次选中
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        
        NSString * strmin = [self getOrAfterAFewDaysAgoWithDate:@"" days:1 back:YES];
        NSDate * minDate = [dateFormatter dateFromString:strmin];
        [viewDatepicker setPickViewMinData:minDate];
        [viewDatepicker setPickViewMaxData:[dateFormatter dateFromString:@"2100-1-1"]];
        
        NSDate * defDate = [dateFormatter dateFromString:str_stark_time];
        [viewDatepicker setDefoultData:defDate];//默认
        viewDatepicker.pickTitle.text = str_stark_time;
    }
    
    [self showPickerData:YES];
}




#pragma mark ===查看添加病例图片===

-(IBAction)btnaddOrLookImage:(id)sender
{
    UIButton * btn = (UIButton *)sender;
    if (btn.tag-100 >= arrayPicture.count)
    {
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"选照片",@"拍照", nil];
        [sheet showInView:self.view];

    }else
    {
        MFMWPhotoBrowser * browse = [[MFMWPhotoBrowser alloc] init];
        browse.mfDelegate = self;
        browse.delegate = self;
        browse.displayDeleteButton = YES;
        [browse setCurrentPhotoIndex:btn.tag-100];
        UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browse];
        [self presentViewController:nc animated:YES completion:nil];
    }
    
}



#pragma mark =======delegate======


#pragma mark photoBrowerNeedDeletePhoto
- (void)photoBrowerNeedDeletePhoto:(MFMWPhotoBrowser *)photoBrowser AtIndex:(int)index
{
    [arrayPicture removeObjectAtIndex:index];
    [self dismissViewControllerAnimated:YES completion:nil];
    [self setCaseImageView];
    
}

//查看大图
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser
{
    return arrayPicture.count;
}

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
{
    MWPhoto * photo = [MWPhoto photoWithImage:[arrayPicture objectAtIndex:index]];
    return photo;
    
}

#pragma mark actionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
  
    if (buttonIndex == 1)
    {
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
            if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
            {
               Alert(alerTitle, @"您的设备不允许[名医主刀]访问您的'相机',请到'设置'里面找到[名医主刀]并打开允许[名医主刀]访问'相机'功能", @"确定")
                return;
            }
        
            UIImagePickerController * picker = [[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.allowsEditing = NO;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;  //相机
            [self presentViewController:picker animated:YES completion:nil];
            
        }else
        {
            Alert(alerTitle, @"您的设备无法使用'相机'", @"确定")
        }
        
    }else if (buttonIndex == 0)
    {
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
        {
            ALAuthorizationStatus state = [ALAssetsLibrary authorizationStatus];
            if (state == ALAuthorizationStatusRestricted || state ==ALAuthorizationStatusDenied)
            {
                 Alert(alerTitle, @"您的设备不允许[名医主刀]访问您的'照片',请到'设置'里面找到[名医主刀]并打开允许[名医主刀]访问'照片'功能", @"确定")
                return;
            }
            QBMFImagePickerController *selectPhoto = [[QBMFImagePickerController alloc] init];
            selectPhoto.QBMFDelegate = self;
            selectPhoto.maximumNumberOfSelection = (9 - [arrayPicture count]);
            [self presentViewController:selectPhoto animated:YES completion:nil];
        
        }else
        {
            Alert(alerTitle, @"您的设备无法使用'照片'", @"确定")
        }
    }
}

#pragma mark - 选择照片发送协议方法 QBMFImagePickerController
- (void)imagePickerController:(QBMFImagePickerController *)imagePickerController didSelectPhtos:(NSArray *)photos
{
    //[arrayImages addObject:UIImageJPEGRepresentation([photos objectAtIndex:imageIndex],0.3)];//上传数组
    [arrayPicture addObjectsFromArray:photos];
    [self setCaseImageView];
}


//====================

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    
    if (image)
    {
        [arrayPicture addObject:image];
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
    [self setCaseImageView];
}



#pragma mark pickDelegate
-(void)toolBarDoneClick:(id)sender
{
    if (selectBeginDate)//开始
    {
        [btndataBegin setTitle:viewDatepicker.pickTitle.text forState:UIControlStateNormal];
        str_stark_time = viewDatepicker.pickTitle.text;
        
        NSString * strtime = [self getOrAfterAFewDaysAgoWithDate:str_stark_time days:7 back:YES];
        [btndateEnd setTitle:strtime forState:UIControlStateNormal];
        str_end_time = strtime;
    }
    else
    {
        [btndateEnd setTitle:viewDatepicker.pickTitle.text forState:UIControlStateNormal];
        str_end_time = viewDatepicker.pickTitle.text;
    }
}

#pragma mark showDataView
-(void)showPickerData:(BOOL)show
{
    for (NSLayoutConstraint *constraints in [self.view constraints]) {
        if (constraints.firstItem == self.view && constraints.secondItem == viewDatepicker && constraints.firstAttribute == NSLayoutAttributeBottom)
        {
            [UIView animateWithDuration:0.2 animations:^{
                constraints.constant = (show?0:-206);
                [self.view layoutIfNeeded];
            } completion:^(BOOL finished)
             {
             }];
            break;
        }
    }
    
    btnCancel.hidden = !show;
}



#pragma mark textFieldDelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    textNow = textField;
    [self changeViewFrame];
}


-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//    if([self stringContainsEmoji:string])//yes是表情
//    {
//        return NO;
//    }
    if ([string isEqualToString:@"\n"])
    {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}

#pragma mark textFieldDelegate
-(void)textViewDidBeginEditing:(UITextView *)textView
{
    textNow = nil;
    [self changeViewFrame];
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
//    if([self stringContainsEmoji:text])//yes是表情
//    {
//        return NO;
//    }
    
    if ([text isEqualToString:@"\n"])
    {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}


#pragma mark //当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keyHeight = keyboardRect.size.height;
    
    [self changeViewFrame];
}

-(void)changeViewFrame
{
    int bottomDistance;
    if (textNow == nil)
    {
       bottomDistance = appScreenHeight -  txv_Disease_Dp.bottom-64;//键盘预留高度
    }else
    {
       bottomDistance = appScreenHeight - textNow.bottom-64;//键盘预留高度
    }
    
    int content = bottomDistance - (keyHeight + 30);//键盘到text得间距
    
    if (content < 0)
    {
        [scrollMain setContentOffset:CGPointMake(0,-content) animated:YES];
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [textNow resignFirstResponder];
    [txv_Disease_Dp resignFirstResponder];
}

-(void)textfieldContentWithoutAnimate:(NSLayoutConstraint *)constraint
{
    [UIView animateWithDuration:0.2 animations:^{
        
        [scrollMain setContentOffset:CGPointMake(0,0) animated:NO];
        
    }];
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [textNow resignFirstResponder];
    [txv_Disease_Dp resignFirstResponder];
}


#pragma mark alertViewDelege
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.cancelButtonIndex != buttonIndex)
    {
        [self updateDataWithReservationList];
    }
}

//提交信息
-(void)updateDataWithReservationList
{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]initWithCapacity:0];
    [dic setObject:[gProjConfig.dicUserData objectForKey:USER_tel] forKey:@"booking[username]"];
    [dic setObject:[gProjConfig.dicUserData objectForKey:USER_token] forKey:@"booking[token]"];
    [dic setObject:[gProjConfig.dicUserData objectForKey:USER_tel] forKey:@"booking[mobile]"];//账号
    
    [dic setObject:txtUserName.text forKey:@"booking[contact_name]"];//患者名称
    [dic setObject:@"" forKey:@"booking[disease_pid]"];//身份证号
    
    if(self.reservationDoctor)
    {
      [dic setObject:self.doctorData.ID forKey:@"booking[doctor_id]"];//普通医生
    }
    else
    {
      [dic setObject:self.doctorData.ID forKey:@"booking[expteam_id]"];//团队
    }
    
    [dic setObject:txtDisease_name.text forKey:@"booking[disease_name]"];//疾病名称
    [dic setObject:txv_Disease_Dp.text forKey:@"booking[disease_detail]"];//疾病详情
    [dic setObject:str_stark_time forKey:@"booking[date_start]"];//开始时间
    [dic setObject:str_end_time forKey:@"booking[date_end]"];//结束时间
    
    SetHUDStartText(@"提交数据中...")

//    NSString * strUrl = [NSString stringWithFormat:@"/booking?os=ios&appv=15&api=5"];
//   
//    if (!self.oldUrl)
   // NSString * strUrl = [NSString stringWithFormat:@"%@?os=ios&appv=15&api=5",self.doctorData.actionUrl];

    [[HttpClient manager]POST:self.doctorData.actionUrl
                   parameters:dic
    success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         if (arrayPicture.count>0)
         {
             NSString * strUrl = [[responseObject objectForKey:requestDataKey] objectForKey:@"actionUrl"];
             NSString * strid = [[responseObject objectForKey:requestDataKey] objectForKey:@"booking_id"];
             [self updateImageWithBoolingID:strid url:strUrl];
       
         }else
         {
             SetHUDFinishedText(@"提交成功")
         }
         
    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         SetHUDHidden;
         HUDShowRequestError(error.domain, self.view);
    }];
}


-(void)hudWasHidden:(MBProgressHUD *)hud
{
    AppointmentViewController * appView =[[AppointmentViewController alloc]initWithNibName:@"AppointmentViewController" bundle:nil];
    [self.navigationController pushViewController:appView animated:YES];
    
    NSMutableArray * array =[[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
    [array removeObjectAtIndex:array.count-2];
    
    self.navigationController.viewControllers = array;
  //  NSLog(@"===%@",self.navigationController.viewControllers);
}

#pragma mark updateImage
-(void)updateImageWithBoolingID:(NSString *)ID url:(NSString *)strUrl
{
    
    updateIndex = 0;
    for (int i = 0; i < arrayPicture.count; i++)
    {
        SetHUDStartText(@"上传图片中..")
        
        NSMutableDictionary * dicData = [[NSMutableDictionary alloc]initWithCapacity:0];
        [dicData setObject:[gProjConfig.dicUserData objectForKey:USER_tel] forKey:@"bookingFile[username]"];
        [dicData setObject:[gProjConfig.dicUserData objectForKey:USER_token] forKey:@"bookingFile[token]"];
        [dicData setObject:ID forKey:@"bookingFile[booking_id]"];
        
        [[HttpClient manager]UPLOADIMAGE:strUrl
                        uploadImage:[arrayPicture objectAtIndex:i]
                        parameters:dicData
        success:^(AFHTTPRequestOperation *operation, id responseObject)
        {
            if (updateIndex == (arrayPicture.count-1))  //3
            {
               SetHUDFinishedText(@"上传成功")
                return;
            }
            updateIndex = updateIndex+1;
        } failure:^(AFHTTPRequestOperation *operation, NSError *error)
        {
            SetHUDHidden;
            HUDShowRequestError(error.domain, self.view);
        }];
        
        /*
        NSString * strGetToken = [NSString stringWithFormat:@"http://192.168.31.118/file.myzd.com/api/uploadtoken?tableName=%@",APPOINTtableName];
        NSLog(@"strGetToken==url:%@",strGetToken);
        
        NSTimeInterval time=[[NSDate date] timeIntervalSince1970];
        long long int currentTime=(long long int)time;
        NSString *tempTime = [NSString stringWithFormat:@"%lld",currentTime];
        NSData *imageData = UIImageJPEGRepresentation([arrayPicture objectAtIndex:updateIndex],1);
        
        [[HttpClient manager]UPLOADIMAGEQINIU:strGetToken
                                  uploadImage:[arrayPicture objectAtIndex:i]
                              uploadImageName:[NSString stringWithFormat:@"ImageName%@.jpg",tempTime]
                                   parameters:nil
                                      success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             //向服务器提交数据
             NSLog(@"==%@",responseObject);
             
             if ([responseObject isKindOfClass:[NSDictionary class]])
             {
                 NSInteger length = [imageData length]/1000;
                 
                 NSMutableDictionary * dic = [[NSMutableDictionary alloc]initWithCapacity:0];
                 [dic setObject:APPOINTtableName forKey:@"appFile[tableName]"];
                 
                 [dic setObject:[NSString stringWithFormat:@"%ld",(long)length] forKey:@"appFile[size]"];
                 [dic setObject:@"jpg" forKey:@"appFile[type]"];
                 
                 [dic setObject:NullObjToString([[responseObject objectForKey:requestDataKey] objectForKey:@"remoteDomain"]) forKey:@"appFile[remoteDomain]"];//地址url
                 [dic setObject:NullObjToString([[responseObject objectForKey:requestDataKey] objectForKey:@"reomteKey"]) forKey:@"appFile[remoteKey]"];
                 
                 [dic setObject:ID forKey:@"appFile[bookingId]"];
                 
                 [dic setObject:[gProjConfig.dicUserData objectForKey:USER_tel] forKey:@"appFile[username]"];
                 [dic setObject:[gProjConfig.dicUserData objectForKey:USER_token] forKey:@"appFile[token]"];
                 
                 if (updateIndex == (arrayPicture.count-1))  //3
                 {
                     [self updateData:dic isEnd:YES];
                 }
                 else
                 {
                     [self updateData:dic isEnd:NO];
                 }
                 
                 updateIndex = updateIndex+1;
             }
             
         } failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             SetHUDHidden;
             HUDShowRequestError(error.domain, self.view);
         }];
         */
    }
}

/*
#pragma mark 七牛上传成功 数据保存至数据库接口
-(void)updateData:(NSMutableDictionary *)requestDic isEnd:(BOOL)end
{
    NSString * strUpdateUrl = @"http://192.168.31.118/file.myzd.com/api/saveappfile";
    [[HttpClient manager]POST:strUpdateUrl
                   parameters:requestDic
                      success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         DLog(@"=上传图片成功后回调=%@",responseObject);
         if (end)
         {
             SetHUDFinishedText(@"上传成功")
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         SetHUDHidden;
         HUDShowRequestError(error.domain, self.view);
     }];
}
*/

#pragma mark 几天前或者后
-(NSString *)getOrAfterAFewDaysAgoWithDate:(NSString *)strDate days:(int)day back:(BOOL)backDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate * date;
    if([strDate isEqualToString:@""])
    {
      date = [NSDate date];//给定的时间
    }else
    {
       date = [dateFormatter dateFromString:strDate];
    }
    
    NSDate * lastDay = [NSDate dateWithTimeInterval:-24*60*60*day sinceDate:date];//前几天
    NSDate * nextDat = [NSDate dateWithTimeInterval:24*60*60*day sinceDate:date];//后几天
    
    if (backDay)
       return [dateFormatter stringFromDate:nextDat];
    else
       return [dateFormatter stringFromDate:lastDay];
    
    return 0;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
